from django import forms
from django.contrib.auth.forms import AuthenticationForm
from django.utils import timezone
import logging
from coach.models.user_models import User

# 配置日志
logger = logging.getLogger(__name__)

class CustomLoginForm(AuthenticationForm):
    username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}))

    def clean(self):
        cleaned_data = super().clean()
        username = cleaned_data.get('username')
        
        # 验证失败时记录日志
        if not self.is_valid():
            # 记录尝试登录的用户名、时间和IP（如果有）
            request = self.request
            ip_address = request.META.get('REMOTE_ADDR', 'unknown') if request else 'unknown'
            
            logger.warning(
                f"登录失败 - 用户名: {username}, "
                f"时间: {timezone.now()}, "
                f"IP地址: {ip_address}, "
                f"错误信息: {self.errors}"
            )
        
        return cleaned_data